const CryptoJS = require("crypto-js");

export default function (req, res) {
  // 将密钥从环境变量中提取
  const KEY_PWD = process.env.DES_KEY;
  const IV_SIZE = 8;

  // 读取请求体中的数据
  const input = req.body.input;
  
  try {
    try {
        const complexKey = [
          process.env.part1,
          process.env.part2,
          process.env.part3,
          process.env.part4,
          process.env.part5,
          process.env.part6,
          process.env.part7,
          process.env.part8,
        ].join("");
        const keyBytes = CryptoJS.enc.Utf8.parse(complexKey);
    const inputBytes = CryptoJS.enc.Utf8.parse(input);
    const ivBytes = CryptoJS.lib.WordArray.random(IV_SIZE);
    const encrypted = CryptoJS.DES.encrypt(inputBytes, keyBytes, {
      iv: ivBytes,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    const ciphertext = ivBytes
      .concat(encrypted.ciphertext)
    // 发送加密后的数据
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/json");
    res.end(ciphertext.toString());
  } catch (error) {
    console.error(error);
    res.statusCode = 500;
    res.end(JSON.stringify({ error: "Encryption failed" }));
  }
}
